package fanjingzhu.check.dao.impl;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import publics.model.Balance;
import publics.model.Company;
import publics.model.Enterprise;
import fanjingzhu.check.dao.EnterpriseDao;

@Component("enterpriseDao")
public class EnterpriseDaoImpl implements EnterpriseDao{
	
	HibernateTemplate hibernateTemplate;// hibernate的spring代理模版

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	// 注入 hibernate模版
	@Resource(name = "hibernateTemplate")	
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
		System.out.println("hibernateTemplate injected in enterpriseDaoImpl!");
		// 测试用，实际运行中可去掉这句
	}
    
	public Integer save(Enterprise enterprise) {
		return (Integer)this.getHibernateTemplate().save(enterprise);
	}
	
	public boolean delete(Enterprise enterprise) {
		try {
			 this.getHibernateTemplate().delete(enterprise);
		} catch (DataAccessException e) {
			return false;
		}
	    return true;
	}

	public boolean deleteById(Integer enterpriseId) {
//		System.out.println("DaoInpl里 enterpriseId="+enterpriseId);
		try{// 使用try 来确定 删除是否成功
			this.getHibernateTemplate().delete(this.getHibernateTemplate().get(Enterprise.class, enterpriseId));
		}catch (DataAccessException e) {
			return false;
		}
		return true;
	}
	
	public boolean update(Enterprise enterprise) {
		try{
			this.getHibernateTemplate().update(enterprise);
		}catch (DataAccessException e) {
			return false;
		}
		return true;
	}
	
	public Enterprise findById(Integer enterpriseId) {
		return this.getHibernateTemplate().get(Enterprise.class, enterpriseId);
	}

	@SuppressWarnings("unchecked")
	public List<Enterprise> findByPage(final String hql, final int offset, final int pageSize) {
		List<Enterprise> list = this.getHibernateTemplate().executeFind(
				new HibernateCallback() {
					public Object doInHibernate(Session session) throws HibernateException ,SQLException {
						//执行hibernate分页查询
						List<Enterprise> result = session.createQuery(hql)
						.setFirstResult(offset)
						.setMaxResults(pageSize)
						.list();
						return result;
					}
				}
				);
		
		return list;
	}

	public int findByCount(String sql) {
		return this.getHibernateTemplate().find(sql).size();
	}
}
